package com.njtech.pet.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author lxj
 * Date 2020-05-22 16:56
 * Description 用户登录拦截器
 */

public class UserLoginInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //获取session
        HttpSession session = httpServletRequest.getSession();
        System.out.println("进入UserInterceptor");
        if (session.getAttribute("user") != null) {
            //如果已经登录，则不用拦截
            return true;
        }
        //如果没有登陆，重定向至首页
        httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/NoLogin");
        System.err.println("用户没有登录，重定向至" + httpServletRequest.getContextPath() + "/NoLogin");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
